﻿using CqCore.Collections;
using System;
using System.Collections.Generic;

namespace CqCore.Messaging
{
    public class MessageHeader : DataDictionary
    {
        public MessageHeader()
        {
            Id = Guid.NewGuid().ToString("N");
            Time = DateTime.Now;
        }

        public string Id { get => Value<string>("id"); set => Value<string>("id", value); }
        public string Type { get => Value<string>("type"); set => Value<string>("type", value); }
        /// <summary>
        /// 消息来源地址
        /// 例如：<ClientId>.<DeviceId>、<ModuleId>.<NodeId>等
        /// </summary>
        public Uri Source
        {
            get
            {
                var value = Value<string>("source");
                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }
                else
                {
                    return new Uri(value);
                }
            }
            set
            {
                Value<string>("source", value.ToString());
            }
        }
        /// <summary>
        /// 消息目标地址
        /// 例如：<ClientId>、<ClientId>.<DeviceId>、<ModuleId>、<ModuleId>.<NodeId>等
        /// </summary>
        public Uri Target
        {
            get
            {
                var value = Value<string>("target");
                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }
                else
                {
                    return new Uri(value);
                }
            }
            set
            {
                Value<string>("target", value.ToString());
            }
        }
        public string Token { get => Value<string>("token"); set => Value<string>("token", value); }
        public string Version { get => Value<string>("version"); set => Value<string>("version", value); }
        public DateTime Time { get => Value<DateTime>("time"); set => Value<DateTime>("time", value); }
    }

    public static class UriExtensions
    {
        public static string ToTopic(this Uri context)
        {
            var items = new List<string>();

            items.Add(context.Scheme);
            items.Add(context.Host);
            if (context.Port > 0) { items.Add(context.Port.ToString()); }
            if (!string.IsNullOrEmpty(context.UserInfo)) { items.Add(context.UserInfo); }
            var path = context.AbsolutePath.Trim('/');
            if (!string.IsNullOrEmpty(path)) { items.AddRange(path.Split('/')); }

            return string.Join(".", items);
        }
    }
}
